import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";

// import Home from "../pages/Home.vue";
// import About from "../pages/About.vue";

//配置映射关系
const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: () =>
      import(/* webpackChunkName:"home-chunk" */ "../pages/Home.vue"), //魔法注释 打包后的名字
    meta: {
      name: "cccc",
      age: 18,
    },
    children: [
      {
        path: "",
        redirect: "/home/message",
      },
      {
        path: "message",
        component: () => import("../pages/HomeMessage.vue"),
      },
      {
        path: "shops",
        component: () => import("../pages/HomeShops.vue"),
      },
    ],
  },
  {
    path: "/about",
    name: "about",
    component: () =>
      import(/* webpackChunkName:"about-chunk" */ "../pages/About.vue"),
  },
  {
    path: "/user/:username/id/:id",
    component: () => import("../pages/User.vue"),
  },
  {
    path: "/login",
    component: () => import("../pages/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../pages/NotFound.vue"),
  },
];

//创建一个路由对象
const router = createRouter({
  routes,
  history: createWebHistory(),
});

//动态添加顶级路由对象
router.addRoute({
  path: "/category",
  component: () => import("../pages/Category.vue"),
});

//添加二级路由对象
router.addRoute("home", {
  path: "category",
  component: () => import("../pages/Category.vue"),
});

//导航守卫
let counter = "";
//to:Route对象  去哪里
//form:Route对象  从哪来
/**
 * 返回值问题:
 *    1.false: 不进行导航
 *    2.undefined或者不写返回值: 进行默认导航
 *    3.字符串: 路径, 跳转到对应的路径中
 *    4.对象: 类似于 router.push({path: "/login", query: ....})
 */
router.beforeEach((to, form) => {
  console.log(`进行了${++counter}次路由跳转`);
  // if (to.path.indexOf("/home") !== -1) {
  //   return "/login"
  // }

  if (to.path !== "/login") {
    const token = window.localStorage.getItem("token");
    if (!token) {
      return "/login";
    }
  }
});
export default router;
